/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.ipo.mm.ejb.entities.Actions;
import org.ipo.mm.ejb.entities.Document;
import org.ipo.mm.ejb.entities.Meeting;
import org.ipo.mm.ejb.entities.Representative;
import org.ipo.mm.ejb.entities.User;
import org.ipo.mm.ejb.facade.actions.ActionsFacadeLocal;
import org.ipo.mm.ejb.facade.document.DocumentFacadeLocal;
import org.ipo.mm.ejb.facade.log.LogFacadeLocal;
import org.ipo.mm.ejb.facade.meeting.MeetingFacadeLocal;
import org.ipo.mm.ejb.facade.representative.RepresentativeFacadeLocal;
import org.ipo.mm.web.formbeans.MeetingBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.UTFEncoder;

/**
 *
 * @author makcro
 */
public class MeetingAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;

        MeetingBean mb = (MeetingBean) form;
        List<Representative> reprs = lookupRepresentativeFacade().findAll();
       
        

        MessageResources mResources = getResources(request);
        String saveOperaton = mResources.getMessage(getLocale(request), "gen_create");
        String updateOperation = mResources.getMessage(getLocale(request), "gen_update");
        String removeRepr = mResources.getMessage(getLocale(request), "meetings_remove_repr");
        String searchRepr = mResources.getMessage(getLocale(request), "meetings_search_repr");
        String addRepr = mResources.getMessage(getLocale(request), "meetings_add_repr");
        String removeDoc = mResources.getMessage(getLocale(request), "meetings_remove_doc");
        String createRepr = mResources.getMessage(getLocale(request), "repr_create");
        String addAction = mResources.getMessage(getLocale(request), "meetings_action_add");
        String updateAction = mResources.getMessage(getLocale(request), "actions_update");

        String operation = mb.getOperation();
         operation = UTFEncoder.encode(operation);
//        operation = UTFEncoder.clearSerbianLetters(operation);
     
        if (isCancelled(request)) {
            actionForward = executeCancel(request, mb, mapping);
            request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);
        } else if (searchRepr.equals(operation)) {
            actionForward = executeSearchRepresentatives(request, mb, mapping);
        } else if (addRepr.equals(operation)) {
            actionForward = executeAddRepresentatives(request, mb, mapping);
        } else if (removeRepr.equals(operation)) {
            actionForward = executeRemoveRepresentative(request, mb, mapping);
        } else if (saveOperaton.equals(operation)) {
            actionForward = executeSave(request, mb, mapping);
            request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);

        } else if (removeDoc.equals(operation)) {
            actionForward = executeRemoveDocuments(request, mb, mapping);
        } else if (updateOperation.equals(operation)) {
            actionForward = executeUpdate(request, mb, mapping);
            request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);
        } else if (createRepr.equals(operation)) {
            actionForward = new ActionForward("/protected/dispatch.do?method=showCreateReprForm", true);
            request.getSession().setAttribute(ConstantManager.SESSION_MEETING_RESET_FORM, false);

        } else if (addAction.equals(operation)) {
            actionForward = executeAddAction(request, mb, mapping);
        } else if(updateAction.equals(operation)){
        actionForward = executeUpdateAction(mb, request, mapping);
        }



        return actionForward;
    }

    private ActionForward executeSearchRepresentatives(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) {

        ActionForward actionForward = null;

        String searchQuery = UTFEncoder.encode(mb.getSearchQuery());

        List<Representative> results = lookupRepresentativeFacade().search(searchQuery);

        mb.setReprSearchResults(results.toArray(new Representative[results.size()]));

        actionForward = mapping.getInputForward();

        return actionForward;


    }

    private ActionForward executeAddRepresentatives(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) {
        ActionForward actionForward = null;

        int[] selectedRepr = mb.getSelectedRepresentatives();
        //only if user selected one or more search results
        if (selectedRepr != null && selectedRepr.length > 0) {
            RepresentativeFacadeLocal rfl = lookupRepresentativeFacade();
            Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
            String role = mb.getRole();


            if ("Representative".equals(role)) {

                for (int i = 0; i < selectedRepr.length; i++) {
                    int reprPrimaryKey = selectedRepr[i];
                    Representative rpr = rfl.find(reprPrimaryKey);

                    if (!meeting.getRepresentativeCollection().contains(rpr)) {
                        meeting.getRepresentativeCollection().add(rfl.find(reprPrimaryKey));

                    }

                }
                mb.setRepresentatives(selectedRepr);

            } else if ("Organizer".equals(role)) {

                meeting.setOrganizer(rfl.find(selectedRepr[0]));
                mb.setOrganizer(String.valueOf(selectedRepr[0]));
            }

            //mb.setReprSearchResults(new Representative[0]);

        }


        actionForward = mapping.getInputForward();

        return actionForward;
    }

    private ActionForward executeRemoveRepresentative(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) {

        ActionForward actionForward = null;

        int[] selectedRepr = mb.getSelectedReprForRemove();
        if (selectedRepr != null && selectedRepr.length > 0) {
            Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);

            for (int i = 0; i < selectedRepr.length; i++) {
                int reprId = selectedRepr[i];
                Representative fakeRp = new Representative(reprId);

                meeting.getRepresentativeCollection().remove(fakeRp);


            }
        }

        actionForward = mapping.getInputForward();
        return actionForward;
    }

    private ActionForward executeRemoveDocuments(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) {
        ActionForward actionForward = null;

        int[] selectedDocuments = mb.getSelectedDocuments();
        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);

        for (int i = 0; i < selectedDocuments.length; i++) {
            int docId = selectedDocuments[i];
            Document tmpDoc = new Document(docId, meeting);

            meeting.getDocumentCollection().remove(tmpDoc);


        }
        actionForward = mapping.getInputForward();
        return actionForward;
    }

    private ActionForward executeSave(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) throws IOException {
        ActionForward actionForward = null;

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

        //is organizer attached?

        if (meeting.getOrganizer() == null) {
            ActionMessages errors = new ActionMessages();
            errors.add("organizer", new ActionMessage("errors.required"));
            saveErrors(request, errors);

            actionForward = mapping.getInputForward();

        } else {
            Date date = null;
            try {
                date = dateFormat.parse(mb.getDate().trim());
            } catch (ParseException ex) {
                Logger.getLogger(MeetingAction.class.getName()).log(Level.SEVERE, null, ex);
            }


            meeting.setConclusion(UTFEncoder.encode(mb.getConclusion()));
            meeting.setEventName(UTFEncoder.encode(mb.getEventName()));
            meeting.setNote(UTFEncoder.encode(mb.getNote()));
            meeting.setVenue(UTFEncoder.encode(mb.getVenue()));

            meeting.setStartTime(UTFEncoder.encode(mb.getStartTime()));
            meeting.setEndTime(UTFEncoder.encode(mb.getEndTime()));
            meeting.setDraft(mb.isDraft());
            meeting.setDate(date);
            meeting.setUser(user);
            //Collection<Actions> ac = meeting.getMeetingActions();
            //meeting.setMeetingActions(null);
            lookupMeetingFacade().create(meeting);
            //createActions(ac);
            @SuppressWarnings("UseOfObsoleteCollectionType")
            Vector<Document> docs = getFilesAsDocs(mb, meeting);
            createDocuments(docs);
            
            // log
            lookupLogFacade().logCreate(user, ConstantManager.MEETING_NAME, meeting.getEventName());

            notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_CREATE, request);
            request.getSession().setAttribute(ConstantManager.SESSION_MEETING_RESET_FORM, true);

            // remove meeting lock
            
            request.getSession().removeAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
            BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
            bc.pop();
            actionForward = bc.pop().getActionForward();

        }

        return actionForward;
    }

    private Vector<Document> getFilesAsDocs(MeetingBean mb, Meeting m) throws IOException {
        Vector<Document> docs = new Vector<Document>();

        if (mb.getDoc1file().getFileSize() > 0) {
            Document d = new Document();
            d.setMeeting(m);
            d.setFile(mb.getDoc1file().getFileData());
            d.setName(mb.getDoc1Name());
            d.setFileName(mb.getDoc1file().getFileName());
            d.setNote(mb.getDoc1Note());
            docs.add(d);
        }

        if (mb.getDoc2file().getFileSize() > 0) {
            Document d = new Document();
             d.setMeeting(m);
            d.setFile(mb.getDoc1file().getFileData());
            d.setName(mb.getDoc1Name());
            d.setFileName(mb.getDoc1file().getFileName());
            d.setNote(mb.getDoc1Note());
            docs.add(d);
        }

        if (mb.getDoc3file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc3file().getFileData());
            d.setName(mb.getDoc3Name());
            d.setFileName(mb.getDoc3file().getFileName());
            d.setNote(mb.getDoc3Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc4file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc4file().getFileData());
            d.setName(mb.getDoc4Name());
            d.setFileName(mb.getDoc4file().getFileName());
            d.setNote(mb.getDoc4Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc5file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc5file().getFileData());
            d.setName(mb.getDoc5Name());
            d.setFileName(mb.getDoc5file().getFileName());
            d.setNote(mb.getDoc5Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc6file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc6file().getFileData());
            d.setName(mb.getDoc6Name());
            d.setFileName(mb.getDoc6file().getFileName());
            d.setNote(mb.getDoc6Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc7file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc7file().getFileData());
            d.setName(mb.getDoc7Name());
            d.setFileName(mb.getDoc7file().getFileName());
            d.setNote(mb.getDoc7Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc8file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc8file().getFileData());
            d.setName(mb.getDoc8Name());
            d.setFileName(mb.getDoc8file().getFileName());
            d.setNote(mb.getDoc8Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc9file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc9file().getFileData());
            d.setName(mb.getDoc9Name());
            d.setFileName(mb.getDoc9file().getFileName());
            d.setNote(mb.getDoc9Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc10file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc10file().getFileData());
            d.setName(mb.getDoc10Name());
            d.setFileName(mb.getDoc10file().getFileName());
            d.setNote(mb.getDoc10Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc11file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc11file().getFileData());
            d.setName(mb.getDoc1Name());
            d.setFileName(mb.getDoc11file().getFileName());
            d.setNote(mb.getDoc11Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc12file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc12file().getFileData());
            d.setName(mb.getDoc12Name());
            d.setFileName(mb.getDoc12file().getFileName());
            d.setNote(mb.getDoc12Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc13file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc13file().getFileData());
            d.setName(mb.getDoc13Name());
            d.setFileName(mb.getDoc13file().getFileName());
            d.setNote(mb.getDoc13Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc14file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc14file().getFileData());
            d.setName(mb.getDoc14Name());
            d.setFileName(mb.getDoc14file().getFileName());
            d.setNote(mb.getDoc14Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc15file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc15file().getFileData());
            d.setName(mb.getDoc15Name());
            d.setFileName(mb.getDoc15file().getFileName());
            d.setNote(mb.getDoc15Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc16file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc16file().getFileData());
            d.setName(mb.getDoc16Name());
            d.setFileName(mb.getDoc16file().getFileName());
            d.setNote(mb.getDoc16Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc17file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc17file().getFileData());
            d.setName(mb.getDoc17Name());
            d.setFileName(mb.getDoc17file().getFileName());
            d.setNote(mb.getDoc17Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc18file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc18file().getFileData());
            d.setName(mb.getDoc8Name());
            d.setFileName(mb.getDoc18file().getFileName());
            d.setNote(mb.getDoc18Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc19file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc19file().getFileData());
            d.setName(mb.getDoc19Name());
            d.setFileName(mb.getDoc19file().getFileName());
            d.setNote(mb.getDoc19Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc20file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc20file().getFileData());
            d.setName(mb.getDoc20Name());
            d.setFileName(mb.getDoc20file().getFileName());
            d.setNote(mb.getDoc20Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc21file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc21file().getFileData());
            d.setName(mb.getDoc21Name());
            d.setFileName(mb.getDoc21file().getFileName());
            d.setNote(mb.getDoc21Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc22file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc22file().getFileData());
            d.setName(mb.getDoc2Name());
            d.setFileName(mb.getDoc22file().getFileName());
            d.setNote(mb.getDoc22Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc23file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc23file().getFileData());
            d.setName(mb.getDoc23Name());
            d.setFileName(mb.getDoc23file().getFileName());
            d.setNote(mb.getDoc23Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc24file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc24file().getFileData());
            d.setName(mb.getDoc24Name());
            d.setFileName(mb.getDoc24file().getFileName());
            d.setNote(mb.getDoc24Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc25file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc25file().getFileData());
            d.setName(mb.getDoc25Name());
            d.setFileName(mb.getDoc25file().getFileName());
            d.setNote(mb.getDoc25Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc26file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc26file().getFileData());
            d.setName(mb.getDoc26Name());
            d.setFileName(mb.getDoc26file().getFileName());
            d.setNote(mb.getDoc26Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc27file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc27file().getFileData());
            d.setName(mb.getDoc27Name());
            d.setFileName(mb.getDoc27file().getFileName());
            d.setNote(mb.getDoc27Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc28file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc28file().getFileData());
            d.setName(mb.getDoc28Name());
            d.setFileName(mb.getDoc28file().getFileName());
            d.setNote(mb.getDoc28Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc29file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc29file().getFileData());
            d.setName(mb.getDoc29Name());
            d.setFileName(mb.getDoc29file().getFileName());
            d.setNote(mb.getDoc29Note());
            d.setMeeting(m);
            docs.add(d);
        }

        if (mb.getDoc30file().getFileSize() > 0) {
            Document d = new Document();
            
            
            
            d.setFile(mb.getDoc30file().getFileData());
            d.setName(mb.getDoc30Name());
            d.setFileName(mb.getDoc30file().getFileName());
            d.setNote(mb.getDoc30Note());
            d.setMeeting(m);
            docs.add(d);
        }

        return docs;
    }

    private RepresentativeFacadeLocal lookupRepresentativeFacade() {
        try {
            Context c = new InitialContext();
            return (RepresentativeFacadeLocal) c.lookup("java:comp/env/RepresentativeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private MeetingFacadeLocal lookupMeetingFacade() {
        try {
            Context c = new InitialContext();
            return (MeetingFacadeLocal) c.lookup("java:comp/env/MeetingFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private DocumentFacadeLocal lookupDocumentFacade() {
        try {
            Context c = new InitialContext();
            return (DocumentFacadeLocal) c.lookup("java:comp/env/DocumentFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private ActionForward executeCancel(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) {
        request.getSession().setAttribute(ConstantManager.SESSION_MEETING_RESET_FORM, new Boolean(true));
        
        request.getSession().removeAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    private ActionForward executeUpdate(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) throws IOException {


        String date_n = mb.getDate();
        String organizer_id_n = mb.getOrganizer();

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

        meeting.setOrganizer(lookupRepresentativeFacade().find(Integer.valueOf(organizer_id_n)));

        //Update Action//*************//*************
        if(mb.getActionId()!=null && !mb.getActionId().equals("null")){
            Actions updatingAction = new Actions();
            updatingAction.setId(Integer.parseInt(mb.getActionId()));
            Date dueDate = null;
            try {
                dueDate = new SimpleDateFormat("dd/MM/yyyy").parse(mb.getActionDueDate());
            } catch (ParseException ex) {
                Logger.getLogger(MeetingAction.class.getName()).log(Level.SEVERE, null, ex);
            }
            updatingAction.setDueDate(dueDate);
            updatingAction.setName(mb.getActionName());
            updatingAction.setActionText(mb.getActionDesc());
            updatingAction.setStatus(mb.getActionStatus());
            updatingAction.setDeleted(false);
            updatingAction.setMeetingId(meeting);
            int indexOfUpdating = mb.getActions().indexOf(updatingAction);
            mb.getActions().set(indexOfUpdating, updatingAction);
        }
        //*************//*************//*************


        // meeting.setDraft(mb.isDraft());
        // workaround for draft beacuse of struts bug :(
        meeting.setDraft(request.getParameter("draft") != null);

        meeting.setConclusion(UTFEncoder.encode(mb.getConclusion()));
        meeting.setEventName(UTFEncoder.encode(mb.getEventName()));
        meeting.setNote(UTFEncoder.encode(mb.getNote()));
        meeting.setVenue(UTFEncoder.encode(mb.getVenue()));

        meeting.setStartTime(UTFEncoder.encode(mb.getStartTime()));
        meeting.setEndTime(UTFEncoder.encode(mb.getEndTime()));

        try {
            meeting.setDate(new SimpleDateFormat("dd/MM/yyyy").parse(date_n));
        } catch (ParseException ex) {
            Logger.getLogger(MeetingAction.class.getName()).log(Level.SEVERE, null, ex);
        }


        //remove selected docs
        deleteDocuments(meeting);

        Collection<Document> docs = getFilesAsDocs(mb, meeting);

        //create new docs
        createDocuments(docs);

        //meeting.getDocumentCollection().addAll(docs);
       // createActions(meeting.getMeetingActions());

        meeting.setMeetingActions(mb.getActions());
        lookupMeetingFacade().edit(meeting);

        lookupLogFacade().logUpdate(user, ConstantManager.MEETING_NAME, meeting.getEventName());
        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_UPDATE, request);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        ActionForward actionForward = bc.pop().getActionForward();

        request.getSession().setAttribute(ConstantManager.SESSION_MEETING_RESET_FORM, true);

        
        request.getSession().removeAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
        return actionForward;
    }
   private ActionForward executeUpdateAction(MeetingBean meetingBean, HttpServletRequest request, ActionMapping mapping) throws Exception {
        ActionForward actionForward = null;


        String actionDesc = meetingBean.getActionDesc();
        String actionDueDate = meetingBean.getActionDueDate();
        String actionName = meetingBean.getActionName();
        String actionStatus = meetingBean.getActionStatus();
        Date dueDate = new SimpleDateFormat("dd/MM/yyyy").parse(actionDueDate);
        /**
         * determine if request came from actions list, or from meeting update page.
         * if from actions list then retreive action form session atr
         * if from meeting update then get action from collection attached to meeting
         *
         */
        Actions actionsForUpdate = (Actions) request.getSession().getAttribute(ConstantManager.SESSION_ACTIONS_PROCESS);
        actionsForUpdate.setActionText(actionDesc);
        actionsForUpdate.setDueDate(dueDate);
        actionsForUpdate.setName(actionName);
        actionsForUpdate.setStatus(actionStatus);

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);

        if (meeting == null) {
            lookupActionsFacade().edit(actionsForUpdate);
            request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);
        }

        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_UPDATE, request);
        String updatePath =  (String)request.getSession().getAttribute("updateMeetingPath");
        actionForward = new ActionForward( updatePath+"#actionAnchor",true);
        //actionForward = mapping.findForward(ConstantManager.NAVIGATION_CLOSE_WINDOW);

        return actionForward;
    }

    private ActionForward executeAddAction(HttpServletRequest request, MeetingBean mb, ActionMapping mapping) {
        ActionForward actionForward = null;

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

        Actions newActions = new Actions();
        newActions.setMeetingId(meeting);
        newActions.setActionText(mb.getActionDesc());

        try {
            newActions.setDueDate(dateFormat.parse(mb.getActionDueDate()));
        } catch (ParseException ex) {
            Logger.getLogger(MeetingAction.class.getName()).log(Level.SEVERE, null, ex);
        }

        newActions.setName(mb.getActionName());
        newActions.setStatus(mb.getActionStatus());
        newActions.setDeleted(false);


        if(mb.getActions()==null)
        {
            //mb.setActions(Arrays.asList(newActions));
            ArrayList<Actions> act = new ArrayList<Actions>();
            act.add(newActions);
            mb.setActions(act);
        }
        else
        {
            mb.getActions().add(newActions);

        }
        meeting.setMeetingActions(mb.getActions());

        actionForward = mapping.getInputForward();


        return actionForward;
    }

    private void deleteDocuments(Meeting meeting) {
        DocumentFacadeLocal dfl = lookupDocumentFacade();

        Collection<Document> docToKeep = meeting.getDocumentCollection();
        List<Document> allDocs = lookupDocumentFacade().findByMeeting(meeting);


        //remove all documents that are in refreshed meeting but not in currently processed meeting
        for (Document document : allDocs) {
            if (!docToKeep.contains(document)) {
                dfl.remove(document);
            }
        }
    }

    public void createDocuments(Collection<Document> docs) {
        DocumentFacadeLocal dfl = lookupDocumentFacade();
        for (Document document : docs) {
            dfl.create(document);
        }
    }

    private void createActions(Collection<Actions> actionses) {

        ActionsFacadeLocal afl = lookupActionsFacade();

        for (Actions actions : actionses) {
            afl.create(actions);
        }



        //    lookupActionsFacade().create(actionName, actionText, ConstantManager.ACTION_STATUS_PENDING, actionDueDate_Date, meeting);







    }

    private LogFacadeLocal lookupLogFacade() {
        try {
            Context c = new InitialContext();
            return (LogFacadeLocal) c.lookup("java:comp/env/LogFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private ActionsFacadeLocal lookupActionsFacade() {
        try {
            Context c = new InitialContext();
            return (ActionsFacadeLocal) c.lookup("java:comp/env/ActionsFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private void notifyOperatoinStatus(String operationMessageKey, HttpServletRequest request) {

        MessageResources mResources = getResources(request);
        String typeEntityName = mResources.getMessage(getLocale(request), ConstantManager.MEETING_ENTITY_NAME_RES_KEY);

        ActionMessages messages = new ActionMessages();
        ActionMessage actionMessage = new ActionMessage(operationMessageKey, typeEntityName);
        messages.add("operation_status", actionMessage);
        saveMessages(request, messages);

    }

}
